//
//  Client_RF225_MovRplController.swift
//  Wmsmobile
//
//  Created by xuNick on 16/9/10.
//  Copyright © 2016年 www.hd123.com. All rights reserved.
//

import UIKit
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
  switch (lhs, rhs) {
  case let (l?, r?):
    return l < r
  case (nil, _?):
    return true
  default:
    return false
  }
}





class Client_RFGS_fuchaController:  HDFounctionBaseController , HDBarcodeInputCellInputDelegate , HDFounctionBottomViewDelegate , HDSwitchCellDelegate , HDKeyboardInputCellDelegate{
    //MARK: - property
    let dataArrOriginal = [
        [["title" : "容器码"] ,["title" : "总箱数"]],
        [],
        [[ "title" :"商品条码"],["title" : "允许输入"],["title" : "数量"]]
    ]
    var dataArray:[[[String : String]]] = [[[String : String]]]() {
        didSet{
            self.tableView.reloadData()
        }
    }
    var dataArray1:[[String : String]]? {
        didSet{
            self.tableView.reloadData()
        }
    }
    var firstAppear = true
    var piType: String = "0"
    var seletedGID: String?
    var standardSet: [Double]?  //集合规格
    var standardCode: Double? //货品code对应规格
    var numtoUpload: Double? //要提交的数量
    var piKepNum: String?
    var flag: Int = -1 //记录当前商品条码属于哪个集合，默认是-1 不存在
     //对应规格1件的数量
    var inputEnable: Bool = false
    var switchEnable: Bool = false{
        didSet{
            self.tableView.reloadData()
        }
    }
    var piArticleCode : String?{
        didSet{
            self.tableView.reloadData()
        }
    }
    lazy fileprivate var bottomView:HDFounctionBottomView = {
        let view = HDFounctionBottomView(array: ["获取信息","扫描完成"])
        return view
    }()
    
    //MARK: - lifeCycle
    override func viewDidLoad() {
        dataArray = dataArrOriginal
        self.tableView.register(HDBarcodeInputCell.self, forCellReuseIdentifier: "HDBarcodeInputCell")
        self.tableView.register(HDProductInfocell.self, forCellReuseIdentifier: "HDProductInfocell")
        self.tableView.register(HDKeyboardInputCell.self, forCellReuseIdentifier: "HDKeyboardInputCell")
        self.tableView.register(HDSwitchCell.self, forCellReuseIdentifier: "HDSwitchCell")
        self.tableView.register(HDNumberInputCell.self, forCellReuseIdentifier: "HDNumberInputCell")
        self.tableView.register(HDChkBinInfoTableviewCell.self, forCellReuseIdentifier: "HDChkBinInfoTableviewCell")
        self.tableView.addSubview(self.bottomView)
        self.tableView.contentInset.bottom = bottomView.height
        self.bottomView.delegate = self
        super.viewDidLoad()
        self.tableView.allowsSelection = true
        self.tableView.allowsSelectionDuringEditing = true
    }
    override func viewDidAppear(_ animated: Bool) {
        if firstAppear {
            let cell = self.tableView.cellForRow(at: IndexPath(item: 0, section: 0)) as! HDBarcodeInputCell
            cell.state = inputViewState.activated
            firstAppear = false
        }
    }
    //MARK: - delegate
    func clicKKeyboardReturn(_ cell: HDKeyboardInputCell) {
        if let celltext = cell.codeInputView.textField.text {
            if celltext.characters.count > 0 {
                //更新数据集合
                guard Double(celltext) != nil else{
                    self.showMessage("输入的数字不合法", success: false)
                    cell.codeInputView.textField.text = nil
                    return
                }
                numtoUpload = Double(celltext)! * standardCode!
                let arr = self.dataArray1
                self.updateSet()
                if arr! == self.dataArray1!{
                    cell.state = .wrong
                }else{
                    self.goNextCell(cell, nextInsexPath: IndexPath(item: 0, section: 2))
                }
            }else{
                self.showMessage("请输入数量", success: false)
                return
            }
        }else{
            self.showMessage("请输入数量", success: false)
            return
        }
    }
    func clickSwitch(_ isOn: Bool) {
        if isOn{ // 打开
            inputEnable = true
        }else{ //关闭
            inputEnable = false
        }
        if let cell = self.tableView.cellForRow(at: IndexPath(item: 2, section: 2)) as? HDKeyboardInputCell{
//            cell.codeInputView.userInteractionEnabled = isOn
            if isOn{ // 打开
                cell.codeInputView.textField.textColor = UIColor.hexStringToUIColor("#666666")
                cell.titleView.textColor = UIColor.hexStringToUIColor("#666666")
                cell.state = inputViewState.disabled
            }else{ //关闭
                cell.codeInputView.textField.textColor = UIColor.lightGray
                cell.titleView.textColor = UIColor.lightGray
                cell.state = inputViewState.disabled
                self.tableView.scrollToRow(at: IndexPath(item: 0,section: 2), at: UITableViewScrollPosition.middle, animated: false)
                let cell = self.tableView.cellForRow(at: IndexPath(item: 0, section: 2)) as! HDBarcodeInputCell
                cell.state = inputViewState.activated
            }
        }
    }
    
    override func scrollViewDidScroll(_ scrollView: UIScrollView) {
        self.bottomView.y = KscreenHeight - bottomView.height + self.tableView.contentOffset.y
    }
    func clickFounctionBottom(_ position: NSInteger) {
        switch position {
        case 1://点击了扫描完成
            guard numtoUpload != nil else{
                self.showMessage("待完善商品条码和数量", success: false)
                return
            }
            if Float((dataArray1?.first!["复查数量"])!)! == 0 { //复查数量等于0
              self.updKep()
            }else{ //复查数量不等于0时
                self.showAlert("提示", message: "复查数量与货品数量不一致，是否继续", actionLTitle: "取消", actionRTitle: "确定", clickLeft: { 
                    //什么也不做
                   self.tableView.scrollToRow(at: IndexPath(item: 0,section: 2), at: UITableViewScrollPosition.middle, animated: false)
                    let cell = self.tableView.cellForRow(at: IndexPath(item: 0, section: 2)) as! HDBarcodeInputCell
                    cell.state = inputViewState.activated
                    }, clickRight: { 
                      //继续请求
                      self.updKep()
                })
            }
            break
        case 0: //点击了获取信息
            let newVC = self.resetController() as! Client_RFGS_fuchaController
            newVC.getCollection(["piOperator" : (userInfo?.userName)! , "piKepNum" : ""], bodyMethod: "getKep", suffix: "330", success: {  (dict, collections) in
                //展示数据
                newVC.showAlert("提示", message: "篮子号为: \(dict["piKepNum"] ?? "")\n 门店号为: \(dict["poStoreCode"] ?? "")\n位置: \(dict["poPosition"] ?? "")", actionLTitle: "确定", actionRTitle:nil, clickLeft: {
                    newVC.dataArray[0][1].updateValue(dict["poChests"] ?? "", forKey: "text")
                    newVC.dataArray[0][0].updateValue(dict["piKepNum"] ?? "", forKey: "text")
                    var tempArr = collections
                    for i in  0..<tempArr.count {
                        var item = tempArr[i]
                        item.updateValue(item["货品名称"] ?? "", forKey: "left")
                        item.updateValue(item["数量"] ?? "", forKey: "复查数量")
                        item.updateValue(item["件数"] ?? "", forKey: "复查件数")
                        item.updateValue(item["复查件数"] ?? "", forKey: "middle")
                        item.updateValue(item["复查数量"] ?? "", forKey: "right")
                        tempArr[i] = item
                    }
                    newVC.dataArray1 = tempArr
                    //单元格跳转
                    newVC.switchEnable = true
                    newVC.tableView.scrollToRow(at: IndexPath(item: 0,section: 2), at: UITableViewScrollPosition.middle, animated: false)
                    let cell = newVC.tableView.cellForRow(at: IndexPath(item: 0, section: 2)) as! HDBarcodeInputCell
                    cell.state = inputViewState.activated
                    }, clickRight: nil)
                }, failed: {
                    
            })
            break
        default:
            break
        }
    }
    func clicKReturn(_ cell: HDBarcodeInputCell) {
        let indexpath = self.tableView.indexPath(for: cell)!
        let celltext = cell.codeInputView.textField.text
        switch (indexpath as NSIndexPath).section * 100 + (indexpath as NSIndexPath).row  {
        case 0:
            piKepNum = celltext
            self.getCollection(["piOperator" : (userInfo?.userName)! , "piKepNum" : celltext ?? ""], bodyMethod: "getKep", suffix: "330", success: { [weak self] (dict, collections) in
                 //展示数据
                _ = self?.dataArray[0][0].updateValue(celltext ?? "", forKey: "text")
                self?.showAlert("提示", message: "篮子号为: \(dict["piKepNum"] ?? "")\n 门店号为: \(dict["poStoreCode"] ?? "")\n位置: \(dict["poPosition"] ?? "")", actionLTitle: "确定", actionRTitle:nil, clickLeft: {
                    self!.dataArray[0][1].updateValue(dict["poChests"] ?? "", forKey: "text")
                    var tempArr = collections
                    for i in  0..<tempArr.count {
                        var item = tempArr[i]
                        item.updateValue(item["货品名称"] ?? "", forKey: "left")
                        item.updateValue(item["数量"] ?? "", forKey: "复查数量")
                        item.updateValue(item["件数"] ?? "", forKey: "复查件数")
                        item.updateValue(item["复查件数"] ?? "", forKey: "middle")
                        item.updateValue(item["复查数量"] ?? "", forKey: "right")
                        tempArr[i] = item
                    }
                    self!.standardSet = [Double]()
                    for item in collections {
                        self!.standardSet!.append(Double(item["规格数量"] ?? "1") ?? 1.0)
                    }
                        self!.dataArray1 = tempArr
                        //单元格跳转
                        self!.switchEnable = true
                        self?.goNextCell(cell, nextInsexPath: IndexPath(item: 0, section: 2))
                    }, clickRight: nil)
                }, failed: {
                  cell.state = inputViewState.wrong
            })
        case 200:
            if celltext?.characters.count < 1 {
                self.showMessage("请输入商品条码", success: false)
                return
            }
            
            flag = -1 //对比货品集中是否存在该商品条码
            for j in 0..<self.dataArray1!.count {
                let codeArr = self.dataArray1![j]["货品代码"]?.components(separatedBy: ",")
                guard codeArr != nil else{
                    return
                }
                for item in codeArr! {
                    if item == celltext{
                        flag = j
                        seletedGID = self.dataArray1![j]["货品GID"]
                        break
                    }
                }
                if flag != -1 {
                    break
                }
            }
            
            if flag != -1 { //商品存在
                self.getCollection(["piArticleCode" : celltext ?? "" , "piArticleGid" : self.seletedGID ?? "" , "piOperator" : (userInfo?.userName)!] , bodyMethod:  "GetArtQpcInfo", suffix: "330", success: { (dict, collections) in
                    self.piArticleCode = celltext
                    self.dataArray[2][0].updateValue(celltext ?? "", forKey: "text")
                    guard collections.count > 0 else {
                        return
                    }
                    self.standardCode = Double(collections.first!["FQPC"] ?? "1")
                    //条码验证成功
                    //允许输入
                    if self.inputEnable == true {
                        self.goNextCell(cell, nextInsexPath: IndexPath(item: 2, section: 2))
                    }else {
                        //不允许输入,更新集合信息
                        self.numtoUpload = self.standardCode
                        self.updateSet()
                    }
                    }, failed: {
                    cell.state = inputViewState.wrong
                })
                
            }else{ //不存在该商品
                self.showMessage("不存在货品条码\(celltext ?? "")", success: false)
                cell.state = inputViewState.wrong
            }
            break
        default:
            break
        }
        
    }
    //MARK: - private
    //执行最后一步请求
    func updKep(){
    var dataSet = dataArray1
    for i in 0..<(dataSet?.count ?? 0){
    dataSet![i].removeValue(forKey: "left")
    dataSet![i].removeValue(forKey: "middle")
    dataSet![i].removeValue(forKey: "right")
    dataSet![i].updateValue(dataSet![i]["复查数量"] ?? "", forKey: "货品扫描数量")
    dataSet![i].removeValue(forKey: "复查数量")
    dataSet![i].updateValue(dataSet![i]["数量"] ?? "", forKey: "货品数量")
    dataSet![i].removeValue(forKey: "数量")
    }
    self.getData(["piOperator" : (userInfo?.userName)! , "piKepNum" : piKepNum!, "piValue" : StringHandleTool.dictToDataSets(dataSet!)], bodyMethod: "updKep", suffix: "225", success: { (dict) in
    //直接重新进入控制器
    let newVc:HDFounctionBaseController = self.resetController()
        DispatchQueue.main.asyncAfter(deadline:DispatchTime(uptimeNanoseconds: UInt64(1 * Double(NSEC_PER_SEC))), execute: {
            newVc.showMessage("复查完毕", success: true)
        })
    }, failed: { (dict) in
        self.tableView.scrollToRow(at: IndexPath(item: 0 , section: 2), at: UITableViewScrollPosition.middle, animated: false)
        let cell = self.tableView.cellForRow(at: IndexPath(item: 0, section: 2)) as! HDBarcodeInputCell
        cell.state = inputViewState.wrong
    })
    }
    func updateSet(){
        let num = (Double(self.dataArray1![flag]["复查数量"] ?? "0") ?? 0) - (self.numtoUpload ?? 0)
        if num > Double(INT64_MAX) {
            self.showMessage("输入数字过小", success: false)
            return
        }else if num < Double(-INT64_MAX){
            self.showMessage("输入数字过大", success: false)
            return
        }
        if num.truncatingRemainder(dividingBy: 1) == 0 {
            self.dataArray1![flag].updateValue(String(Int64(num)), forKey: "复查数量")
            self.dataArray1![flag].updateValue(String(Int64(num)), forKey: "right")
        }else{
            self.dataArray1![flag].updateValue(String(num), forKey: "复查数量")
            self.dataArray1![flag].updateValue(String(num), forKey: "right")
        }
        let bagNum = Int64(num / (self.standardSet![flag] ))
        let littleNum = num.truncatingRemainder(dividingBy: (self.standardSet![flag] ))
        var numJian = ""
        if littleNum.truncatingRemainder(dividingBy: 1) == 0 {
            numJian = littleNum == 0 ? String(bagNum) : "\(bagNum)+\(Int64(littleNum))"
        }else{
            numJian = littleNum == 0 ? String(bagNum) : "\(bagNum)+\(littleNum)"
        }
        self.dataArray1![flag].updateValue(numJian, forKey: "复查件数")
        self.dataArray1![flag].updateValue(numJian, forKey: "middle")
        self.tableView.scrollToRow(at: IndexPath(item: 0 , section: 2), at: UITableViewScrollPosition.middle, animated: false)
        let cell = self.tableView.cellForRow(at: IndexPath(item: 0, section: 2)) as! HDBarcodeInputCell
        cell.state = inputViewState.activated
    }
    
    override func isEmpty() -> (Bool) {
        if self.dataArray[0][0]["text"] != nil {
            return false
        }else{
            return true
        }
    }
    //MARK: - tableviewDatasource
    override func numberOfSections(in tableView: UITableView) -> Int {
        return dataArray.count
    }
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 1 {
            return dataArray1?.count ?? 1
        }
        return dataArray[section].count
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellOriginal:HDFounctionBaseCell?
        switch ((indexPath as NSIndexPath).section) * 1000 + ((indexPath as NSIndexPath).row) {
        case 0:
            cellOriginal = tableView.dequeueReusableCell(withIdentifier: "HDBarcodeInputCell") as! HDBarcodeInputCell
            let cell = cellOriginal as! HDBarcodeInputCell
            cell.InputDelegate = self
            
        case 2001:
            cellOriginal = tableView.dequeueReusableCell(withIdentifier: "HDSwitchCell") as! HDSwitchCell
            let cell = cellOriginal as! HDSwitchCell
            cell.delegate = self
            cell.info = dataArray[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
            if (indexPath as NSIndexPath).section == 2 {
                cell.switchView.isEnabled = switchEnable
            }
            return cell
        case 1000...1999:
            cellOriginal = tableView.dequeueReusableCell(withIdentifier: "HDChkBinInfoTableviewCell") as! HDChkBinInfoTableviewCell
            let cell = cellOriginal as! HDChkBinInfoTableviewCell
            if let dataArr = dataArray1{
                cell.dict = dataArr[(indexPath as NSIndexPath).row]
                cell.accessoryViewHiden = false
            }else{
                cell.dict = ["middle" : "无数据"]
                cell.accessoryViewHiden = true
            }
            return cell
        case 2000:
            cellOriginal = tableView.dequeueReusableCell(withIdentifier: "HDBarcodeInputCell") as! HDBarcodeInputCell
            let cell = cellOriginal as! HDBarcodeInputCell
            cell.InputDelegate = self
        case 2002:
            cellOriginal = tableView.dequeueReusableCell(withIdentifier: "HDKeyboardInputCell") as! HDKeyboardInputCell
            let cell = cellOriginal as! HDKeyboardInputCell
            cell.info = self.dataArray[2][2]
            cell.precision = 1
            cell.InputDelegate = self
        default:
            cellOriginal = tableView.dequeueReusableCell(withIdentifier: "HDProductInfocell") as! HDProductInfocell
        }
        if !self.reuseFlag {
            if  let  cell = cellOriginal as? inputViewProtocol{
                cell.state = inputViewState.disabled
            }
        }
        cellOriginal!.info = dataArray[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
        return cellOriginal!
    }
    //MARK: - tableViewDelegate
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let position = (indexPath as NSIndexPath).section * 1000 + (indexPath as NSIndexPath).row
        guard position < 2000 && position >= 1000 else {
            self.tableView.deselectRow(at: indexPath, animated: false)
            return
        }
        guard dataArray1 != nil else{
            return
        }
        //弹出需要的控制器
        let vcInfo = self.dataArray1![(indexPath as NSIndexPath).row]
        let vc = HDShowDetailController(info: vcInfo, dataArray: ["货品GID" , "货品代码" , "货品名称" , "复查件数" , "件数" , "复查数量" , "数量" , "规格" , "规格数量" , "拣货位" , "行号"])
        self.navigationController?.pushViewController(vc, animated: true)
    }
    override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        switch section {
        case 2:
            return UIView(frame: CGRect(x: 0, y: 0, width: KscreenWidth, height: 0.1))
        default:
            return nil
        }
    }
    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        //           let sectionHeaders:[String] = [,]
        switch section {
        case 1:
            let view = FounctionSectionHeaderView(headerString: "货品名称,复查件数,复查数量")
            return view
        default:
            return nil
        }
    }
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        switch section {
        case 0,2:
            return 10
        case 1:
            return 40
        default:
            return 0
        }
    }
}
